package han.fetch;

import com.han.http.client.exception.RequestNotExecutedException;
import com.han.http.client.paramter.RequestHeader;
import han.entity.FinanceProjectIdEntity;
import han.entity.FinanceProjectInfoEntity;
import han.exception.MuchRequestException;
import han.exception.NoneCompanyIdException;
import han.exception.OtherDeviceLoginException;
import han.exception.OtherException;
import han.parser.FinanceProjectInfoParser;
import han.proof.Cookie;
import han.sql.InsertThread;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Random;

import static com.han.http.util.Print.printlnErr;
import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/7/18 17:26
 * @dscription: 抓取融资项目线程
 */
public class FinanceProjectInfoThread extends Thread {

    private final Object krLock;
    private Fetcher fetcher;
    private Cookie cookie;
    private List<FinanceProjectIdEntity> idList;
    private InsertThread insertThread;

    FinanceProjectInfoThread(List<FinanceProjectIdEntity> idList, Cookie cookie, Object
            krLock, InsertThread insertThread) {
        this.idList = idList;
        this.cookie = cookie;
        this.krLock = krLock;
        this.insertThread = insertThread;
        fetcher = new Fetcher();
    }

    @Override
    public void run() {
        getProjectInfo();
    }

    /**
     * 抓取融资项目信息
     */
    private void getProjectInfo() {
        //休眠索引
        int sleepIndex = 0;
        //休眠时间，1：休眠18个小时:2：休眠半个小时
        long[] sleepTime = {
                1000 * 60 * 60 * 18,
                1000 * 60 * 30,
        };
        //请求数量
        int requestCount = 0;
        Random random = new Random();
        for (FinanceProjectIdEntity idEntity : idList) {

            int status = cookie.getStatus();
            if (status == 2) {
                //如果cookie不可用,跳出
                printlnInfo(getName() + " " + cookie.getLoginName() + "不可用");
                break;
            }
            //项目编号
            String krId = idEntity.getProjectId();
            boolean isSleep = false;
            int interval = random.nextInt(1000 * 10) + 1000 * 10;
            try {
                //访问目标项目,获取项目信息
                FinanceProjectInfoEntity infoEntity;
                //同步锁
                synchronized (krLock) {
                    infoEntity = getProjectInfoM(krId);
                    /*String name = infoEntity.getFullName();
                    name = "-".equals(infoEntity.getFullName()) ? infoEntity.getName() : name;
                    String[] contact = InfoSupplementer.qiChaCha(name, "PHPSESSID=ejnhu0to2sea4eqjk8fch03fs6; UM_distinctid=165d71a97ea961-07b1e9eed1d85f-6154702a-1fa400-165d71a97eca11; CNZZDATA1254842228=130082512-1536910380-https%253A%252F%252Fwww.baidu.com%252F%7C1536910380; Hm_lvt_3456bee468c83cc63fb5147f119f1075=1536912169; hasShow=1; _uab_collina=153691216965876673017412; acw_tc=b461f59b15369121680836554eb2823728e3d92f47ea34f0c252ebbdb4; _umdata=70CF403AFFD707DFCE60A8EB03D5914878164B3F0A090A35329EA7B475C3A22A90C4E59E30B0C4A2CD43AD3E795C914CA81F8E5F1BE567256B677CB1B4510CF3; Hm_lpvt_3456bee468c83cc63fb5147f119f1075=1536912195");
                    infoEntity.setEmail(contact[0]);
                    infoEntity.setPhoneNumber(contact[1]);
                    infoEntity.setAddress(contact[2]);*/
                    try {
                        Thread.sleep(100);
                        isSleep = true;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //成功获取项目信息,插入待插入容器
                insertThread.insertInsertProjectInfo(infoEntity);
                //访问次数 + 1
                idEntity.setTimes(idEntity.getTimes() + 1);
                cookie.setStatus(0);
                //每次成功抓取,使得休眠索引重置为0
                sleepIndex = 0;
                //访问次数 + 1
                requestCount++;
                printlnInfo(getName() + " " + cookie.getLoginName() + ":" + krId + "抓取成功,已抓取:" + requestCount);
            } catch (MuchRequestException e) {
                cookie.setStatus(1);
                printlnErr(getName() + " " + cookie.getLoginName() + ":Cookie被暂时封了,预备休眠" + sleepTime[sleepIndex] + "毫秒");
                try {
                    //初次休眠时间为sleepIndex[i],后面休眠时间为sleepIndex[1]
                    Thread.sleep(sleepTime[sleepIndex]);
                    sleepIndex = 1;
                } catch (InterruptedException ee) {
                    ee.printStackTrace();
                }
            } catch (NoneCompanyIdException e) {
                printlnErr(getName() + " " + cookie.getLoginName() + ":没有该项目:" + krId);
                //设置删除标志位
                idEntity.setDeleteFlag(1);
            } catch (OtherDeviceLoginException e) {
                printlnInfo(getName() + " " + cookie.getLoginName() + ":你的账号已在其他设备登录");
                cookie.setStatus(2);
                break;
            } catch (Exception e) {
                printlnErr(getName() + " " + cookie.getLoginName() + "未知错误:" + krId);
                e.printStackTrace();
            } finally {
                //设置最后访问时间
                idEntity.setLastRequestTime(new Timestamp(System.currentTimeMillis()));
                //添加抓取后的项目id
                insertThread.insertUpdateProjectId(idEntity);
                //不管成功或者失败,均休眠
                try {
                    if (isSleep) {
                        Thread.sleep(interval);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 使用移动端url获取融资项目信息
     *
     * @param projectId 项目id
     * @return entity
     * @throws OtherException 没有获取到数据
     */
    private FinanceProjectInfoEntity getProjectInfoM(String projectId) throws NoneCompanyIdException,
            MuchRequestException, OtherDeviceLoginException, OtherException {
        String urlStr = "https://rong.36kr.com/api/mobi-investor/v3/company/" + projectId + "?statsRefer=others";
        RequestHeader[] requestHeaders = {
                new RequestHeader("User-Agent", "36kr-Tou-Android/4.1.2 (MI 6; Android 8.0.0; Scale/1920x1080)"),
                new RequestHeader("Cookie", cookie.getCookie()),
                new RequestHeader("Host", "rong.36kr.com"),
                new RequestHeader("Connection", "Keep-Alive"),
                new RequestHeader("Accept-Encoding", "gzip"),
        };
        int generalTimeout = 10;
        FinanceProjectInfoEntity entity = new FinanceProjectInfoEntity();
        entity.setProjectId(projectId);
        try {
            String jsonStr = fetcher.getInfoByGet(urlStr, requestHeaders, generalTimeout, generalTimeout, null);
            if (jsonStr.contains(FinanceProjectId.RESPONSE_CODE[3])) {
                throw new NoneCompanyIdException();
            } else if (jsonStr.contains(FinanceProjectId.RESPONSE_CODE[2])) {
                throw new MuchRequestException();
            } else if (jsonStr.contains(FinanceProjectId.RESPONSE_CODE[4])) {
                throw new OtherDeviceLoginException();
            } else if (!jsonStr.contains(FinanceProjectId
                    .RESPONSE_CODE[0])) {
                throw new OtherException("没有获取到数据" + jsonStr + ",项目id" + projectId);
            }
            entity = FinanceProjectInfoParser.getProjectInfoM(jsonStr);
            //移动端url获取到的数据
            entity.setM(1);
        } catch (IOException | RequestNotExecutedException e) {
            e.printStackTrace();
        }

        return entity;
    }
}
